package com.binguo.wxapi.util;

import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;


public class Sha1 {
		
		  /** 
	     * 定义加密方式 
	     */  
	    private final static String KEY_SHA = "SHA";  
	    private final static String KEY_SHA1 = "SHA-1";  
	    /** 
	     * 全局数组 
	     */  
	    private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",  
	            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };  
	  
	    /** 
	     * 构造函数 
	     */  
	    public Sha1() {  
	  
	    }

	    public static String generateSignAndPostData(
									String phone
									, String securityKey
		){

			Map<String,Object> map=new HashMap<String,Object>();
			map.put("phone", phone == null ? "" : phone);

			String afterChange = null;
			try {

				afterChange = SHA1(map, securityKey);
				System.out.println(afterChange);

				map.put("sign", afterChange);

				return JsonUtil.toJson(map);
			} catch (Exception e) {
			}

			return null;

		}
	  
	  
	    /** 
	     * SHA 加密 
	     * @param data 需要加密的字节数组 
	     * @return 加密之后的字节数组 
	     * @throws Exception 
	     */  
	    public static byte[] encryptSHA(byte[] data) throws Exception {  
	        // 创建具有指定算法名称的信息摘要  
//	        MessageDigest sha = MessageDigest.getInstance(KEY_SHA);  
	        MessageDigest sha = MessageDigest.getInstance(KEY_SHA1);  
	        // 使用指定的字节数组对摘要进行最后更新  
	        sha.update(data);  
	        // 完成摘要计算并返回  
	        return sha.digest();  
	    }  
	  
	    /** 
	     * SHA 加密 
	     * @param data 需要加密的字符串 
	     * @return 加密之后的字符串 
	     * @throws Exception 
	     */  
	    public static String encryptSHA(String data) throws Exception {  
	        // 验证传入的字符串  
	        
	        // 创建具有指定算法名称的信息摘要  
	        MessageDigest sha = MessageDigest.getInstance(KEY_SHA);  
	        // 使用指定的字节数组对摘要进行最后更新  
	        sha.update(data.getBytes());  
	        // 完成摘要计算  
	        byte[] bytes = sha.digest();  
	        // 将得到的字节数组变成字符串返回  
	        return byteArrayToHexString(bytes);  
	    }  
	  
	    /** 
	     * 将一个字节转化成十六进制形式的字符串 
	     * @param b 字节数组 
	     * @return 字符串 
	     */  
	    private static String byteToHexString(byte b) {  
	        int ret = b;  
	        //System.out.println("ret = " + ret);  
	        if (ret < 0) {  
	            ret += 256;  
	        }  
	        int m = ret / 16;  
	        int n = ret % 16;  
	        return hexDigits[m] + hexDigits[n];  
	    }  
	  
	    /** 
	     * 转换字节数组为十六进制字符串 
	     * @param bytes 字节数组 
	     * @return 十六进制字符串 
	     */  
	    private static String byteArrayToHexString(byte[] bytes) {  
	        StringBuffer sb = new StringBuffer();  
	        for (int i = 0; i < bytes.length; i++) {  
	            sb.append(byteToHexString(bytes[i]));  
	        }  
	        return sb.toString();  
	    }  
	  
		
		
	    /** 
	     * SHA1 安全加密算法 
	     * @param maps 参数key-value map集合 
	     * @param securityKey 
	     * @return 
	     * @throws Exception 
	     */  
	    public static String SHA1(Map<String,Object> maps, String securityKey) throws Exception {  
	        //获取信息摘要 - 参数字典排序后字符串  
	        String decrypt = getOrderByLexicographic(maps);
	        //拼接厂商秘钥
	        StringBuffer sb = new StringBuffer(decrypt); 
	        sb.append(securityKey);

	        //apiKeyNUFDJSOAcstmOrderNo201901101803002690data{"bizType":"","distributorId":"","distributorName":"","eventId":"","eventName":""}notifyUrlhttp://devwx.zj.chinaunicom.com/zjunicom-weixin/priviligeOrderController/acceptResultphone13282138659productCodeCMP305689154698608640timeStamp20190326140802
			//apiKeyNUFDJSOAcstmOrderNo201901101803002690data{"bizType":"","distributorId":"","distributorName":"","eventId":"","eventName":""}notifyUrlhttp://devwx.zj.chinaunicom.com/zjunicom-weixin/priviligeOrderController/acceptResultphone13282138659productCodeCMP305689154698608640timeStamp20190326140802cc1745453991ec29bfedd5f80a2d5bf0
			System.out.println(sb.toString());
	        try {  
	            //指定sha1算法  
	            return encryptSHA(sb.toString());  
	        } catch (NoSuchAlgorithmException e) {  
	            e.printStackTrace();  
	            throw new DigestException("签名错误！");  
	        }  
	    }  
	    /** 
	     * 获取参数的字典排序 
	     * @param maps 参数key-value map集合 
	     * @return String 排序后的字符串 
	     */  
	    private static String getOrderByLexicographic(Map<String,Object> maps){  
	        return splitParams(lexicographicOrder(getParamsName(maps)),maps);  
	    }  
	    /** 
	     * 获取参数名称 key 
	     * @param maps 参数key-value map集合 
	     * @return 
	     */  
	    private static List<String> getParamsName(Map<String,Object> maps){  
	        List<String> paramNames = new ArrayList<String>();  
	        for(Map.Entry<String,Object> entry : maps.entrySet()){  
	            paramNames.add(entry.getKey());  
	        }  
	        return paramNames;  
	    }  
	    /** 
	     * 参数名称按字典排序 
	     * @param paramNames 参数名称List集合 
	     * @return 排序后的参数名称List集合 
	     */  
	    private static List<String> lexicographicOrder(List<String> paramNames){  
	        Collections.sort(paramNames);  
	        return paramNames;  
	    }  
	    /** 
	     * 拼接排序好的参数名称和参数值 
	     * @param paramNames 排序后的参数名称集合 
	     * @param maps 参数key-value map集合 
	     * @return String 拼接后的字符串 
	     */  
	    private static String splitParams(List<String> paramNames,Map<String,Object> maps){  
	        StringBuilder paramStr = new StringBuilder();  
	        for(String paramName : paramNames){  
	            paramStr.append(paramName);  
	            for(Map.Entry<String,Object> entry : maps.entrySet()){  
	                if(paramName.equals(entry.getKey())){  
	                    paramStr.append(String.valueOf(entry.getValue()));  
	                }  
	            }  
	        }  
	        return paramStr.toString();  
	    
}
	   

	
	    
	    
	    
	    
	}
